#!/usr/bin/ruby
#!/usr/local/bin/macruby -w

#topdir = '/Volumes/MyBook/Movies'
topdir = '/home/vorlov/Videos'

video_exts = %w[
m4v 3gp nsv ts ty strm rm rmvb m3u ifo mov qt divx xvid bivx vob nrg img
iso pva wmv asf asx ogm m2v avi bin dat dvr-ms mpg mpeg mp4 mkv avc vp3 
svq3 nuv viv dv fli flv rar 001 wpl zip]

require File.join(File.dirname(__FILE__),'find_stacks')
include FindStacks


class Actor <
  Struct.new( :name, :role)
end
class Video <
  Struct.new( :codec, :aspect, :width, :height)
end
class Audio <
  Struct.new( :codec, :language, :channels)
end
class Subtitle <
  Struct.new( :language, :file)
end

class Movie <
  Struct.new( :title, :originaltitle, :sorttitle,
    :set, :rating, :year, :top250, :votes, :outline, :plot,
    :tagline, :runtime, :thumb, :mpaa, :playcount,
    :watched, :id, :trailer, :genre, :credits,
    :fileinfo, :director, :actors )
end
def get_subdirs(topdir)
  Dir.chdir(topdir)
  subdirs = Dir["**/*"].reject {|d| File.file?(d)}
  subdirs <<  topdir 
  subdirs.sort!

end
def movies_list(topdir,dir,video_exts)
  movies = Hash.new
  Dir.chdir(dir)
  mediafiles = Dir["*.{#{video_exts.join(",")}}"].sort.reject {|f| File.directory?(f)}
  files_and_stacks = FindStacks::list(mediafiles)
  files_and_stacks.each do |f|
   a = Movie.new
   f.instance_of?(Hash) ? filenamepath = stacked_path(f,dir) : filenamepath = (File.expand_path(f)) 
   movies[filenamepath] = a
  end
  Dir.chdir(topdir)
  return movies
end
def stacked_path(stack,dir)
  p dir
  files = stack.values.flatten 
  files.each do |f|
    f = dir + '/' + f
    f.gsub!(/\,/,',,')
  end
  path = 'stack://' + files.join(' , ')
end

get_subdirs(topdir).each do |subdir|
#  p subdir
  movies = movies_list(topdir,subdir,video_exts)
  movies.each_key do |m|
    puts m  
  end
end
